import axios from 'axios'
import { getToken, removeToken, removeInfo } from '@/utils/cookie'
import { basePath as baseURL } from '@/config'
import { Toast } from 'vant'
function errorMsg(msg) {
  msg && Toast(msg)
}
const $axios = axios.create({
  baseURL,
  timeout: 10000, // 请求超时时间
  maxContentLength: 10000, // 响应最大大小
  withCredentials: true // 证书
})
$axios.interceptors.request.use(
  (config) => {
    const token = getToken()
    config.headers = {}
    if (token) {
      // 请求头部添加token
      config.headers.Authorization = token
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)
/**
 * 响应拦截器
 * 用于处理loading状态关闭、请求成功回调、响应错误处理
 */
$axios.interceptors.response.use(
  (response) => {
    console.log(response)
    const status = response.status
    const success = response.data.success
    if ((status >= 200 && status < 300) || status === 304) {
      // const pollingStatus = response.data.data.status
      if (success) {
        // 全部json数据
        return Promise.resolve(response.data)
      } else {
        response.data && errorMsg(response.data || '请求有误！')
        return Promise.reject(new Error(response.data || 'Error'))
      }
    } else {
      return Promise.reject(response)
    }
  },
  (error) => {
    console.log('error: ', error.response)
    if (error.response) {
      const data = error.response && error.response.data
      switch (error.response.status) {
        case 401:
          errorMsg('权限不足')
          removeToken()
          removeInfo()
          break
        case 404:
          errorMsg(data.message || '网络请求不存在')
          break
        default:
          errorMsg(data.message)
      }
    } else {
      // 请求超时或者网络有问题
      if (error.message.includes('timeout')) {
        errorMsg('请求超时！请检查网络是否正常')
      } else {
        errorMsg('请求失败，请检查网络是否已连接')
      }
    }
    return Promise.reject(error)
  }
)
export default $axios
